package com.gaeig.base;

import javax.jdo.Transaction;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class JDOTransactionInterceptor implements MethodInterceptor {

  public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Object object;
    Transaction transaction = ApplicationPersistenceManager.getCurrentTransaction();

    boolean startTransactionInThisMethod = false;
    if (!transaction.isActive()) {
      transaction.begin();
      startTransactionInThisMethod = true;
    }
    try {
      object = methodInvocation.proceed();
      if (startTransactionInThisMethod) {
        transaction.commit();
      }
    } catch (Throwable throwable) {
      if (startTransactionInThisMethod) {
        transaction.rollback();
      }
      throw throwable;
    }
    return object;
  }
}
